#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <unistd.h>

#define MAX_MAC_ADDR_LEN 18

// 获取网卡MAC地址
int get_mac_address(const char *ifname, char *mac_addr) {
    struct ifreq ifr;
    int sockfd;

    // 创建套接字
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("socket");
        return -1;
    }

    // 设置接口名称
    strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
    ifr.ifr_name[IFNAMSIZ - 1] = '\0';

    // 获取MAC地址
    if (ioctl(sockfd, SIOCGIFHWADDR, &ifr) < 0) {
        perror("ioctl");
        close(sockfd);
        return -1;
    }

    // 格式化MAC地址
    snprintf(mac_addr, MAX_MAC_ADDR_LEN, "%02x:%02x:%02x:%02x:%02x:%02x",
             (unsigned char)ifr.ifr_hwaddr.sa_data[0],
             (unsigned char)ifr.ifr_hwaddr.sa_data[1],
             (unsigned char)ifr.ifr_hwaddr.sa_data[2],
             (unsigned char)ifr.ifr_hwaddr.sa_data[3],
             (unsigned char)ifr.ifr_hwaddr.sa_data[4],
             (unsigned char)ifr.ifr_hwaddr.sa_data[5]);

    close(sockfd);
    return 0;
}

int main() {
    char mac_addr[MAX_MAC_ADDR_LEN];
    const char *ifname = "eth0";  // 假设使用eth0网卡

    if (get_mac_address(ifname, mac_addr) == 0) {
        printf("Unique ID (MAC Address): %s\n", mac_addr);
    } else {
        printf("Failed to get MAC address.\n");
    }

    return 0;
}
